package com.itlong.cloud.controller.operate;

import com.alibaba.fastjson.JSON;
import com.itlong.cloud.POJO.DTO.operate.OperateAdInfoGetPageDTO;
import com.itlong.cloud.POJO.DTO.operate.OperateSaveAdInfoDTO;
import com.itlong.cloud.POJO.DTO.operate.OperateUpdateAdInfoDTO;
import com.itlong.cloud.POJO.DTO.operate.UploadImageDTO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.operate.OperateAdGetOneVO;
import com.itlong.cloud.POJO.VO.operate.OperateAdVO;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.AuthAccessRequired;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.AdTypeEnum;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.FileCatalogEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.OperateErrorCodeEnum;
import com.itlong.cloud.noncore.commons.IUploadImageServiceClient;
import com.itlong.cloud.project.operate.IOperateAdManageServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.page.Page;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * <desc>
 *      运营—运营管理模块—广告管理。
 * <desc/>
 *
 * @createDate 2017/10/19.
 */
@RestController
@RequestMapping("/marketer/ad")
public class OperateAdManageController extends BaseController {

    private static final Logger LOG = LoggerFactory.getLogger(OperateAdManageController.class);

    //广告管理
    @Autowired
    IOperateAdManageServiceClient iOperateAdManageServiceClient;

    @Autowired
    IUploadImageServiceClient iUploadImageServiceClient;

     /**
      * <desc>
      *      上传图片资源。
      * <desc/>
      *
      * @param  httpServletRequest 图片http请求
      * @return
      * @author shengen.T
      * @createDate 2017/10/19
      */
     @LoggerInfo(operateDesc = LogDescConstant.UPLOAD_AD_IMAGE_LOG_DESC)
     @RequestMapping(path = "/uploadImg" , method = RequestMethod.POST)
     @ResponseBody
    public Object uploadImg(HttpServletRequest httpServletRequest){
         MessageVO messageVO;

         String imgUrl = ""; //返回图片链接地址
         String imgBase64 ="";  //图片base64编码字符串
         String imgExt = "jpg|jpeg|png|bmp|BMP|GIF|JPG|PNG|JPEG";
        try{
            String imgData = httpServletRequest.getParameter("imgData");
            if (StringUtils.isBlank(imgData)) {
                imgData = httpServletRequest.getAttribute("imgData") == null ? null : httpServletRequest.getAttribute("imgData").toString();
            }
            if(StringUtils.isBlank(imgData)){
                return new MessageVO(OperateErrorCodeEnum.IMAGE_RESOURCE_EMPTY_ERR.getErrorCode());
            }
            String imgType = imgData.substring(imgData.indexOf("/") + 1, imgData.indexOf(";"));

            if((StringUtils.isBlank(imgType))||(!imgExt.contains(imgType))){
               return new MessageVO(OperateErrorCodeEnum.IMAGE_TYPE_ANVALID_ERR.getErrorCode());
            }
            imgBase64 = imgData.substring(imgData.indexOf(",") + 1, imgData.length());
            UploadImageDTO saveDTO  = new UploadImageDTO();
            saveDTO.setImgBase64(imgBase64);
            saveDTO.setImgType(imgType);
            saveDTO.setFileCatalogName(FileCatalogEnum.ADVERTISING_FILE.getType());
            imgUrl = iUploadImageServiceClient.uploadImg(saveDTO);
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),"",imgUrl);
        } catch (Exception e){
            throw new DataAccessException("【运营_运营管理_广告管理upload】上传图片资源失败",e);
        }
        return messageVO;
    }


    /**
     * <desc>
     *      保存广告信息。
     * <desc/>
     *
     * @param  jsonString 请求参数
     * @return
     * @author shengen.T
     * @createDate 2017/10/13
     */
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.SAVE_ADINFO_LOG_DESC)
    @RequestMapping(path = "/saveAd" , method = RequestMethod.POST)
    @ResponseBody
    public Object saveAd( String jsonString){
        MessageVO messageVO;
        try {
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            jsonString=request.getAttribute("jsonString")==null?null:request.getAttribute("jsonString").toString();
            OperateSaveAdInfoDTO AdInfoDTO = JSON.parseObject(jsonString,OperateSaveAdInfoDTO.class);
            AdInfoDTO.setSystemType(1);
            //请求对象不能为空
            if(null == AdInfoDTO){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //广告标题
            if(StringUtils.isBlank(AdInfoDTO.getTitle())){
                return new MessageVO(OperateErrorCodeEnum.AD_TITLE_EMPTY_ERR.getErrorCode());
            }
            //项目编号不能为空
            if(StringUtils.isBlank(AdInfoDTO.getProjectIds())){
                return new MessageVO(OperateErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            //状态判断
            if((null == AdInfoDTO.getStatus()) || (AdInfoDTO.getStatus() != DataStatusEnum.NORMAL.getType() &&
                    AdInfoDTO.getStatus() != DataStatusEnum.BAN.getType())){
                return new MessageVO(OperateErrorCodeEnum.AD_STATUS_ANVALID_ERR.getErrorCode());
            }
            //发布平台 1代表App 2代表小程序 3代表家半径物业宝APP
            if ((null == AdInfoDTO.getPublishPlatform()) || (AdInfoDTO.getPublishPlatform() != 1 &&
                    AdInfoDTO.getPublishPlatform() != 2 && AdInfoDTO.getPublishPlatform() != 3)) {
                return new MessageVO(OperateErrorCodeEnum.AD_PUBLISH_PLATFORM_TYPE_IS_EMPTY.getErrorCode());
            }
            //所属板块
            if((null == AdInfoDTO.getType())||(AdInfoDTO.getType()!= AdTypeEnum.HOME_PLATE.getType() &&
                    AdInfoDTO.getType()!=AdTypeEnum.SERVICE_PLATE.getType()&&
                    AdInfoDTO.getType()!= AdTypeEnum.PROPERTY_PLATE.getType())){
                return new MessageVO(OperateErrorCodeEnum.AD_TYPE_ANVALID_ERR.getErrorCode());
            }
            //判断推送时间
            if(StringUtils.isBlank(AdInfoDTO.getPublishStartDate()) ||
                    StringUtils.isBlank(AdInfoDTO.getPublishEndDate())){
               return new MessageVO(OperateErrorCodeEnum.AD_PUBLISH_TIME_EMPTY_ERR.getErrorCode());
            }
            //图片信息
            if((AdInfoDTO.getImgInfoVO()==null)||(AdInfoDTO.getImgInfoVO().size()<1)){
                return new MessageVO(OperateErrorCodeEnum.AD_IMGINFO_EMPTY_ERR.getErrorCode());
            }
            iOperateAdManageServiceClient.saveAd(AdInfoDTO);
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【运营_运营管理_广告管理save】保存广告信息失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      修改广告信息。
     * <desc/>
     *
     * @param  jsonString
     * @return
     * @author shengen.T
     * @createDate 2017/10/17
     */
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.UPDATE_ADINFO_LOG_DESC)
    @RequestMapping(path = "/updateAd" , method = RequestMethod.POST)
    @ResponseBody
    public Object updateAd(String jsonString){
        MessageVO messageVO;
        try {
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            jsonString=request.getAttribute("jsonString")==null?null:request.getAttribute("jsonString").toString();
            OperateUpdateAdInfoDTO AdInfoDTO =JSON.parseObject(jsonString,OperateUpdateAdInfoDTO.class);
            AdInfoDTO.setSystemType(1);
            //请求对象不能为空
            if(null == AdInfoDTO){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //广告ID
            if(StringUtils.isBlank(AdInfoDTO.getAdId())){
                return new MessageVO(OperateErrorCodeEnum.AD_ID_EMPTY_ERR.getErrorCode());
            }
            //广告标题
            if(StringUtils.isBlank(AdInfoDTO.getTitle())){
                return new MessageVO(OperateErrorCodeEnum.AD_TITLE_EMPTY_ERR.getErrorCode());
            }
            //项目编号不能为空
            if(StringUtils.isBlank(AdInfoDTO.getProjectIds())){
                return new MessageVO(OperateErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            //状态判断
            if((null == AdInfoDTO.getStatus()) || (AdInfoDTO.getStatus() != DataStatusEnum.NORMAL.getType() &&
                    AdInfoDTO.getStatus() != DataStatusEnum.BAN.getType())){
                return new MessageVO(OperateErrorCodeEnum.AD_STATUS_ANVALID_ERR.getErrorCode());
            }
            //发布平台 1代表App 2代表小程序 3代表家半径物业宝APP
            if ((null == AdInfoDTO.getPublishPlatform()) || (AdInfoDTO.getPublishPlatform() != 1 &&
                    AdInfoDTO.getPublishPlatform() != 2 && AdInfoDTO.getPublishPlatform() != 3)) {
                return new MessageVO(OperateErrorCodeEnum.AD_PUBLISH_PLATFORM_TYPE_IS_EMPTY.getErrorCode());
            }
            //所属板块
            if((null == AdInfoDTO.getType())||(AdInfoDTO.getType()!= AdTypeEnum.HOME_PLATE.getType() &&
                    AdInfoDTO.getType()!=AdTypeEnum.SERVICE_PLATE.getType()&&
                    AdInfoDTO.getType()!= AdTypeEnum.PROPERTY_PLATE.getType())){
                return new MessageVO(OperateErrorCodeEnum.AD_TYPE_ANVALID_ERR.getErrorCode());
            }
            //判断推送时间
            if(StringUtils.isBlank(AdInfoDTO.getPublishStartDate()) ||
                    StringUtils.isBlank(AdInfoDTO.getPublishEndDate())){
                return new MessageVO(OperateErrorCodeEnum.AD_PUBLISH_TIME_EMPTY_ERR.getErrorCode());
            }
            //图片信息
            if((AdInfoDTO.getImgInfoVO()==null)||(AdInfoDTO.getImgInfoVO().size()<1)){
                return new MessageVO(OperateErrorCodeEnum.AD_IMGINFO_EMPTY_ERR.getErrorCode());
            }
            iOperateAdManageServiceClient.updateAd(AdInfoDTO);
            messageVO = new MessageVO(AdInfoDTO.getAdId(), BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【运营_运营管理_广告管理update】修改广告信息失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      批量发布广告。
     * <desc/>
     *
     * @param  adIds 广告ID列表
     * @return
     * @author shengen.T
     * @createDate 2017/10/17
     */
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.PUBLISH_ADINFO_LOG_DESC)
    @RequestMapping(path = "/publishAd" , method = RequestMethod.POST)
    @ResponseBody
    public Object publishAd(String adIds){
        MessageVO messageVO;
        try{
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            adIds=request.getAttribute("adIds")==null?null:request.getAttribute("adIds").toString();
            if(StringUtils.isBlank(adIds)){
                return new MessageVO(OperateErrorCodeEnum.AD_ID_EMPTY_ERR.getErrorCode());
            }
            iOperateAdManageServiceClient.publishAd(adIds);
            messageVO = new MessageVO(adIds, BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【运营_运营管理_广告管理publish】发布广告信息失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      批量删除广告。
     * <desc/>
     *
     * @param  adIds 广告ID列表
     * @return
     * @author shengen.T
     * @createDate 2017/10/17
     */
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.DEL_ADINFO_LOG_DESC)
    @RequestMapping(path = "/deleteAd" , method = RequestMethod.POST)
    @ResponseBody
    public Object deleteAd(String adIds){
        MessageVO messageVO;
        try{
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            adIds=request.getAttribute("adIds")==null?null:request.getAttribute("adIds").toString();
            if(StringUtils.isBlank(adIds)){
                return new MessageVO(OperateErrorCodeEnum.AD_ID_EMPTY_ERR.getErrorCode());
            }
            iOperateAdManageServiceClient.deleteAd(adIds);
            messageVO = new MessageVO(adIds, BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【运营_运营管理_广告管理delete】批量删除广告失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *     设置广告状态。
     * <desc/>
     *
     * @param  adId 广告ID
     * @return
     * @author shengen.T
     * @createDate 2017/10/17
     */
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.SET_ADSTATUS_LOG_DESC)
    @RequestMapping(path = "/setAdStatus" , method = RequestMethod.POST)
    @ResponseBody
    public Object setAdStatus(String adId ,Integer status){
        MessageVO messageVO;
        try{
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            adId=request.getAttribute("adId")==null?null:request.getAttribute("adId").toString();
            status=request.getAttribute("status")==null?null:(Integer)request.getAttribute("status");
            //判断广告ID
            if(StringUtils.isBlank(adId)){
                return new MessageVO(OperateErrorCodeEnum.AD_ID_EMPTY_ERR.getErrorCode());
            }
            //状态判断
            if((null == status) || (status != DataStatusEnum.NORMAL.getType() &&
                    status != DataStatusEnum.BAN.getType())){
                return new MessageVO(OperateErrorCodeEnum.AD_STATUS_ANVALID_ERR.getErrorCode());
            }
            iOperateAdManageServiceClient.setAdStatus(adId,status);
            messageVO = new MessageVO(adId+"|"+status, BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【运营_运营管理_广告管理setStatus】设置广告状态失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *     获取广告详细信息。
     * <desc/>
     *
     * @param  adId 广告ID
     * @return
     * @author shengen.T
     * @createDate 2017/10/17
     */
    @RequestMapping(path = "/getAdInfo" , method = RequestMethod.POST)
    @ResponseBody
    public Object getAdInfo(String adId ){
        MessageVO messageVO;
        try {
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            adId=request.getAttribute("adId")==null?null:request.getAttribute("adId").toString();
            if(StringUtils.isBlank(adId)){
                return new MessageVO(OperateErrorCodeEnum.AD_ID_EMPTY_ERR.getErrorCode());
            }
            OperateAdGetOneVO adVO = iOperateAdManageServiceClient.getAdInfo(adId);
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),adVO);
        }catch (Exception e){
            throw new DataAccessException("【运营_运营管理_广告管理getOne】获取广告详细信息失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      条件查询广告信息列表。
     * <desc/>
     *
     * @param  pageDTO 请求查询参数
     * @return
     * @author shengen.T
     * @createDate 2017/10/17
     */
    @AuthAccessRequired
    @RequestMapping(path = "/getAdInfoPage" , method = RequestMethod.POST)
    @ResponseBody
    public Object getAdInfPage(OperateAdInfoGetPageDTO pageDTO){
        MessageVO messageVO;
        try{
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            pageDTO= HttpProtocolUtil.parseRequestParamToDTO(OperateAdInfoGetPageDTO.class,request);
            Page<OperateAdVO> AdInfoPage = null;
            if(null == pageDTO){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            pageDTO.setSystemType(1);
            AdInfoPage = iOperateAdManageServiceClient.getAdInfoPage(pageDTO);
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),AdInfoPage);
        }catch (Exception e){
            throw new DataAccessException("【运营_运营管理_广告管理getPage】条件查询广告信息列表失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      审核广告
     * </desc>
     *
     * @param pageDTO
     * @return
     * @Author Zhu.yj
     * @createDate  2020/12/24
     */
    @RequestMapping(value = "audit", method = RequestMethod.POST)
    public Object auditAd(OperateAdInfoGetPageDTO pageDTO, HttpServletRequest request){
        try{
            pageDTO = HttpProtocolUtil.parseRequestParamToDTO(OperateAdInfoGetPageDTO.class, request);
            if (pageDTO == null || StringUtils.isBlank(pageDTO.getAdId()) || StringUtils.isBlank(pageDTO.getAuditStatus())){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            iOperateAdManageServiceClient.audit(pageDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【运营_运营管理_广告管理】审核通过失败", e);
        }
    }


}
